package com.rickpan.controller;

import com.rickpan.annotation.RequirePermission;
import com.rickpan.annotation.VipFeature;
import com.rickpan.dto.common.ApiResponse;
import com.rickpan.dto.request.*;
import com.rickpan.dto.response.*;
import com.rickpan.entity.Team;
import com.rickpan.entity.TeamMember;
import com.rickpan.entity.TeamInviteCode;
import com.rickpan.enums.Permission;
import com.rickpan.service.TeamService;
import com.rickpan.service.TeamMemberService;
import com.rickpan.service.TeamInviteCodeService;
import com.rickpan.service.UserOnlineService;
import com.rickpan.entity.User;
import com.rickpan.repository.UserRepository;
import com.rickpan.repository.TeamRepository;
import com.rickpan.repository.TeamMemberRepository;
import com.rickpan.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Optional;

/**
 * 团队管理控制器
 */
@Tag(name = "团队管理", description = "团队相关接口")
@RestController
@RequestMapping("/api/teams")
public class TeamController {

    private static final Logger logger = LoggerFactory.getLogger(TeamController.class);

    @Autowired
    private TeamService teamService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TeamRepository teamRepository;

    @Autowired
    private TeamMemberRepository teamMemberRepository;

    @Autowired
    private TeamMemberService teamMemberService;

    @Autowired
    private TeamInviteCodeService inviteCodeService;

    @Autowired
    private UserOnlineService userOnlineService;

    /**
     * 创建团队
     */
    @Operation(summary = "创建团队", description = "管理员创建团队")
    @PostMapping
    @VipFeature(value = "TEAM_CREATE", description = "团队创建")
    @RequirePermission(value = {Permission.TEAM_CREATE})
    public ApiResponse<TeamResponse> createTeam(@Valid @RequestBody CreateTeamRequest request) {
        logger.info("创建团队请求: {}", request.getName());

        Long userId = SecurityUtils.getCurrentUserId();
        
        // 创建团队实体
        Team team = new Team();
        team.setName(request.getName());
        team.setDescription(request.getDescription());
        team.setMaxMembers(request.getMaxMembers() != null ? request.getMaxMembers() : 50);
        team.setCreatorId(userId);
        team.setTeamAvatarUrl(request.getTeamAvatarUrl());
        
        Team createdTeam = teamService.createTeam(team);
        return ApiResponse.success("团队创建成功，等待管理员审核", TeamResponse.from(createdTeam));
    }

    /**
     * 获取我的团队列表
     */
    @Operation(summary = "获取我的团队列表", description = "获取用户参与的所有团队")
    @GetMapping("/my")
    public ApiResponse<List<TeamResponse>> getMyTeams() {
        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("=== 获取我的团队列表 ===");
        logger.info("当前用户ID: {}", userId);

        List<Team> teams = teamService.findTeamsByUserId(userId);
        logger.info("查询到的团队数量: {}", teams.size());

        for (Team team : teams) {
            logger.info("团队: id={}, name={}, status={}, creatorId={}",
                team.getId(), team.getName(), team.getStatus(), team.getCreatorId());
        }

        List<TeamResponse> teamResponses = teams.stream()
                .map(TeamResponse::from)
                .toList();
        logger.info("返回的团队响应数量: {}", teamResponses.size());
        logger.info("========================");

        return ApiResponse.success("获取成功", teamResponses);
    }

    /**
     * 获取我创建的团队数量
     */
    @Operation(summary = "获取我创建的团队数量", description = "获取当前用户创建的团队总数")
    @GetMapping("/my/created/count")
    public ApiResponse<Long> getMyCreatedTeamCount() {
        Long userId = SecurityUtils.getCurrentUserId();
        long createdTeamCount = teamRepository.countByCreatorId(userId);
        return ApiResponse.success("获取成功", createdTeamCount);
    }

    /**
     * 调试：获取所有团队（仅开发环境）
     */
    @GetMapping("/debug/all")
    public ApiResponse<List<TeamResponse>> getAllTeamsForDebug() {
        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("=== 调试：获取所有团队 ===");
        logger.info("当前用户ID: {}", userId);

        // 直接查询所有团队
        List<Team> allTeams = teamRepository.findAll();
        logger.info("数据库中总团队数量: {}", allTeams.size());

        for (Team team : allTeams) {
            logger.info("团队: id={}, name={}, status={}, creatorId={}, currentMembers={}",
                team.getId(), team.getName(), team.getStatus(), team.getCreatorId(), team.getCurrentMembers());
        }

        // 查询该用户的团队成员记录
        List<TeamMember> userMemberships = teamMemberRepository.findByUserId(userId);
        logger.info("用户{}的团队成员记录数量: {}", userId, userMemberships.size());

        for (TeamMember member : userMemberships) {
            logger.info("成员记录: teamId={}, userId={}, role={}, status={}",
                member.getTeamId(), member.getUserId(), member.getRole(), member.getStatus());
        }

        List<TeamResponse> teamResponses = allTeams.stream()
                .map(TeamResponse::from)
                .toList();
        logger.info("========================");

        return ApiResponse.success("调试获取成功", teamResponses);
    }

    /**
     * 获取待审核团队列表（管理员）
     */
    @Operation(summary = "获取待审核团队列表", description = "管理员获取待审核的团队列表，支持分页")
    @GetMapping("/pending")
    @RequirePermission(value = {Permission.ADMIN_TEAM_APPROVE}, requireAdmin = true)
    public ApiResponse<Page<TeamResponse>> getPendingTeams(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "asc") String sortDir) {

        logger.info("=== 获取待审核团队列表 ===");
        logger.info("分页参数: page={}, size={}, sortBy={}, sortDir={}", page, size, sortBy, sortDir);

        // 创建分页参数
        Sort sort = Sort.by(sortDir.equalsIgnoreCase("desc") ?
            Sort.Direction.DESC : Sort.Direction.ASC, sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);

        // 查询待审核团队
        Page<Team> pendingTeams = teamService.findByStatus(Team.Status.PENDING, pageable);
        logger.info("查询到待审核团队数量: {}", pendingTeams.getTotalElements());

        // 转换为响应对象，并填充创建者信息
        Page<TeamResponse> teamResponses = pendingTeams.map(team -> {
            TeamResponse response = TeamResponse.from(team);
            // 查询创建者用户名
            try {
                User creator = userRepository.findById(team.getCreatorId()).orElse(null);
                if (creator != null) {
                    response.setCreatorName(creator.getUsername());
                } else {
                    response.setCreatorName("未知用户");
                }
            } catch (Exception e) {
                logger.warn("获取创建者信息失败: teamId={}, creatorId={}", team.getId(), team.getCreatorId());
                response.setCreatorName("未知用户");
            }
            return response;
        });

        return ApiResponse.success("获取成功", teamResponses);
    }

    /**
     * 获取团队详情
     */
    @Operation(summary = "获取团队详情", description = "获取指定团队的详细信息")
    @GetMapping("/{id}")
    public ApiResponse<TeamResponse> getTeamDetail(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();

        // 检查用户是否为团队成员
        if (!teamMemberService.isTeamMember(id, userId)) {
            return ApiResponse.error("无权限查看该团队信息");
        }

        Optional<Team> team = teamService.findById(id);
        if (team.isPresent()) {
            return ApiResponse.success("获取成功", TeamResponse.from(team.get()));
        } else {
            return ApiResponse.error("团队不存在");
        }
    }

    /**
     * 更新团队信息
     */
    @Operation(summary = "更新团队信息", description = "团队管理员更新团队基本信息")
    @PutMapping("/{id}")
    @RequirePermission(Permission.TEAM_MANAGE)
    public ApiResponse<TeamResponse> updateTeam(@PathVariable Long id,
                                       @Valid @RequestBody UpdateTeamRequest request) {
        logger.info("更新团队信息: teamId={}", id);

        Long userId = SecurityUtils.getCurrentUserId();
        
        // 检查用户是否为团队管理员
        if (!teamMemberService.isTeamAdmin(id, userId)) {
            return ApiResponse.error("只有团队管理员可以更新团队信息");
        }
        
        Optional<Team> teamOpt = teamService.findById(id);
        if (!teamOpt.isPresent()) {
            return ApiResponse.error("团队不存在");
        }
        
        Team team = teamOpt.get();
        team.setName(request.getName());
        team.setDescription(request.getDescription());
        team.setMaxMembers(request.getMaxMembers());
        team.setTeamAvatarUrl(request.getTeamAvatarUrl());
        
        Team updatedTeam = teamService.updateTeam(team);
        return ApiResponse.success("更新成功", TeamResponse.from(updatedTeam));
    }

    /**
     * 删除团队
     */
    @Operation(summary = "删除团队", description = "团队所有者删除团队")
    @DeleteMapping("/{id}")
    @RequirePermission(Permission.TEAM_DELETE)
    public ApiResponse<Void> deleteTeam(@PathVariable Long id) {
        logger.info("删除团队: teamId={}", id);

        Long userId = SecurityUtils.getCurrentUserId();
        
        // 检查用户是否为团队所有者
        if (!teamMemberService.isTeamOwner(id, userId)) {
            return ApiResponse.error("只有团队所有者可以删除团队");
        }
        
        teamService.deleteTeam(id);
        return ApiResponse.success("团队删除成功");
    }

    /**
     * 审核团队（管理员）
     */
    @Operation(summary = "审核团队", description = "管理员审核团队申请")
    @PutMapping("/{id}/approve")
    @RequirePermission(value = {Permission.ADMIN_TEAM_APPROVE}, requireAdmin = true)
    public ApiResponse<Team> approveTeam(@PathVariable Long id, 
                                        @RequestBody Map<String, Boolean> request) {
        logger.info("审核团队: teamId={}, approved={}", id, request.get("approved"));
        
        Boolean approved = request.get("approved");
        if (approved == null) {
            return ApiResponse.error("请指定审核结果");
        }
        
        Team team;
        if (approved) {
            team = teamService.approveTeam(id);
        } else {
            team = teamService.rejectTeam(id);
        }
        
        return ApiResponse.success("审核完成", team);
    }

    /**
     * 获取团队成员列表
     */
    @Operation(summary = "获取团队成员列表", description = "获取团队所有成员信息")
    @GetMapping("/{id}/members")
    public ApiResponse<List<TeamMemberResponse>> getTeamMembers(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();

        // 检查用户是否为团队成员
        if (!teamMemberService.isTeamMember(id, userId)) {
            return ApiResponse.error("无权限查看团队成员");
        }

        List<TeamMember> members = teamMemberService.findByTeamId(id);
        List<TeamMemberResponse> memberResponses = members.stream()
                .map(member -> {
                    TeamMemberResponse response = TeamMemberResponse.from(member);
                    // 查询用户信息
                    try {
                        User user = userRepository.findById(member.getUserId()).orElse(null);
                        if (user != null) {
                            response.setUsername(user.getUsername());
                            response.setNickname(user.getRealName()); // User实体中是realName字段
                            response.setAvatarUrl(user.getAvatarUrl());
                        }
                    } catch (Exception e) {
                        logger.warn("获取用户信息失败: userId={}", member.getUserId());
                    }
                    return response;
                })
                .toList();
        return ApiResponse.success("获取成功", memberResponses);
    }

    /**
     * 添加团队成员
     */
    @Operation(summary = "添加团队成员", description = "团队管理员邀请新成员")
    @PostMapping("/{id}/members")
    @RequirePermission(Permission.TEAM_INVITE)
    public ApiResponse<TeamMemberResponse> addTeamMember(@PathVariable Long id,
                                                @Valid @RequestBody AddMemberRequest request) {
        logger.info("添加团队成员: teamId={}, userId={}", id, request.getUserId());

        Long operatorId = SecurityUtils.getCurrentUserId();
        
        // 检查操作者是否为团队管理员
        if (!teamMemberService.isTeamAdmin(id, operatorId)) {
            return ApiResponse.error("只有团队管理员可以邀请成员");
        }
        
        TeamMember newMember = new TeamMember();
        newMember.setTeamId(id);
        newMember.setUserId(request.getUserId());
        newMember.setRole(request.getRole() != null ? request.getRole() : TeamMember.Role.MEMBER);
        newMember.setStatus(TeamMember.Status.ACTIVE);
        
        TeamMember addedMember = teamMemberService.addMember(newMember);
        return ApiResponse.success("成员添加成功", TeamMemberResponse.from(addedMember));
    }

    /**
     * 移除团队成员
     */
    @Operation(summary = "移除团队成员", description = "团队管理员移除成员")
    @DeleteMapping("/{id}/members/{userId}")
    @RequirePermission(Permission.TEAM_REMOVE_MEMBER)
    public ApiResponse<Void> removeTeamMember(@PathVariable Long id,
                                             @PathVariable Long userId) {
        logger.info("移除团队成员: teamId={}, userId={}", id, userId);

        Long operatorId = SecurityUtils.getCurrentUserId();

        // 检查操作者是否为团队管理员
        if (!teamMemberService.isTeamAdmin(id, operatorId)) {
            return ApiResponse.error("只有团队管理员可以移除成员");
        }

        // 检查是否尝试删除自己
        if (operatorId.equals(userId)) {
            return ApiResponse.error("不能移除自己");
        }

        teamMemberService.removeMember(id, userId);
        return ApiResponse.success("成员移除成功");
    }

    /**
     * 更新成员角色
     */
    @Operation(summary = "更新成员角色", description = "团队管理员更新成员角色")
    @PutMapping("/{id}/members/{userId}")
    @RequirePermission(Permission.TEAM_MANAGE)
    public ApiResponse<TeamMemberResponse> updateMemberRole(@PathVariable Long id,
                                                   @PathVariable Long userId,
                                                   @Valid @RequestBody UpdateMemberRoleRequest request) {
        logger.info("更新成员角色: teamId={}, userId={}, newRole={}", id, userId, request.getRole());

        Long operatorId = SecurityUtils.getCurrentUserId();
        
        // 检查操作者是否为团队管理员
        if (!teamMemberService.isTeamAdmin(id, operatorId)) {
            return ApiResponse.error("只有团队管理员可以更新成员角色");
        }
        
        TeamMember updatedMember = teamMemberService.updateMemberRole(id, userId, request.getRole());
        return ApiResponse.success("角色更新成功", TeamMemberResponse.from(updatedMember));
    }

    /**
     * 生成团队邀请码
     */
    @Operation(summary = "生成团队邀请码", description = "团队管理员生成邀请码")
    @PostMapping("/{id}/invite-code")
    @RequirePermission(Permission.TEAM_INVITE)
    public ApiResponse<TeamInviteCodeResponse> generateInviteCode(@PathVariable Long id,
                                                         @Valid @RequestBody GenerateInviteCodeRequest request) {
        logger.info("生成团队邀请码: teamId={}", id);

        Long userId = SecurityUtils.getCurrentUserId();

        // 检查用户是否为团队管理员
        if (!teamMemberService.isTeamAdmin(id, userId)) {
            return ApiResponse.error("只有团队管理员可以生成邀请码");
        }

        TeamInviteCode inviteCode = inviteCodeService.generateInviteCode(
            id, userId, request.getInviteRole(), request.getExpireTime(), request.getMaxUses());

        return ApiResponse.success("邀请码生成成功", TeamInviteCodeResponse.from(inviteCode));
    }

    /**
     * 获取团队邀请码列表
     */
    @Operation(summary = "获取团队邀请码列表", description = "团队管理员查看邀请码")
    @GetMapping("/{id}/invite-codes")
    public ApiResponse<List<TeamInviteCodeResponse>> getTeamInviteCodes(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();

        // 检查用户是否为团队管理员
        if (!teamMemberService.isTeamAdmin(id, userId)) {
            return ApiResponse.error("只有团队管理员可以查看邀请码");
        }

        List<TeamInviteCode> inviteCodes = inviteCodeService.getActiveInviteCodes(id);
        List<TeamInviteCodeResponse> inviteCodeResponses = inviteCodes.stream()
                .map(TeamInviteCodeResponse::from)
                .toList();
        return ApiResponse.success("获取成功", inviteCodeResponses);
    }

    /**
     * 通过邀请码加入团队
     */
    @Operation(summary = "通过邀请码加入团队", description = "用户通过邀请码加入团队")
    @PostMapping("/join/{inviteCode}")
    public ApiResponse<TeamMemberResponse> joinTeamByInviteCode(@PathVariable String inviteCode) {
        logger.info("通过邀请码加入团队: inviteCode={}", inviteCode);

        Long userId = SecurityUtils.getCurrentUserId();

        try {
            TeamMember member = inviteCodeService.joinTeamByInviteCode(inviteCode, userId);
            return ApiResponse.success("成功加入团队", TeamMemberResponse.from(member));
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 转移团队所有权
     */
    @Operation(summary = "转移团队所有权", description = "团队所有者转移所有权给其他成员")
    @PutMapping("/{id}/transfer-ownership")
    @RequirePermission(Permission.TEAM_MANAGE)
    public ApiResponse<TeamMemberResponse> transferOwnership(@PathVariable Long id,
                                                   @Valid @RequestBody TransferOwnershipRequest request) {
        logger.info("转移团队所有权: teamId={}, newOwnerId={}", id, request.getNewOwnerId());

        Long currentUserId = SecurityUtils.getCurrentUserId();

        // 检查当前用户是否为团队所有者
        if (!teamMemberService.isTeamOwner(id, currentUserId)) {
            return ApiResponse.error("只有团队所有者可以转移所有权");
        }

        // 检查新所有者是否为团队成员
        if (!teamMemberService.isTeamMember(id, request.getNewOwnerId())) {
            return ApiResponse.error("新所有者必须是团队成员");
        }

        try {
            TeamMember newOwner = teamMemberService.transferOwnership(id, currentUserId, request.getNewOwnerId());
            return ApiResponse.success("所有权转移成功", TeamMemberResponse.from(newOwner));
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 禁用邀请码
     */
    @Operation(summary = "禁用邀请码", description = "团队管理员禁用邀请码")
    @PutMapping("/{id}/invite-codes/{codeId}/disable")
    @RequirePermission(Permission.TEAM_MANAGE)
    public ApiResponse<Void> disableInviteCode(@PathVariable Long id,
                                              @PathVariable Long codeId) {
        logger.info("禁用邀请码: teamId={}, codeId={}", id, codeId);

        Long userId = SecurityUtils.getCurrentUserId();

        try {
            inviteCodeService.disableInviteCode(codeId, userId);
            return ApiResponse.success("邀请码已禁用");
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 刷新邀请码
     */
    @Operation(summary = "刷新邀请码", description = "团队管理员刷新邀请码")
    @PutMapping("/{id}/invite-codes/{codeId}/refresh")
    @RequirePermission(Permission.TEAM_MANAGE)
    public ApiResponse<TeamInviteCodeResponse> refreshInviteCode(@PathVariable Long id,
                                                        @PathVariable Long codeId) {
        logger.info("刷新邀请码: teamId={}, codeId={}", id, codeId);

        Long userId = SecurityUtils.getCurrentUserId();

        try {
            TeamInviteCode refreshedCode = inviteCodeService.refreshInviteCode(codeId, userId);
            return ApiResponse.success("邀请码已刷新", TeamInviteCodeResponse.from(refreshedCode));
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取团队成员在线状态
     *
     * 功能说明：
     * 1. 验证用户是否为团队成员
     * 2. 获取团队所有成员列表
     * 3. 批量查询成员在线状态
     * 4. 组装返回数据，包含在线状态统计信息
     *
     * @param id 团队ID
     * @return 包含成员在线状态信息的响应数据
     */
    @Operation(summary = "获取团队成员在线状态", description = "获取团队所有成员的实时在线状态")
    @GetMapping("/{id}/members/online-status")
    @RequirePermission(Permission.TEAM_VIEW)
    public ApiResponse<Map<String, Object>> getTeamMembersOnlineStatus(@PathVariable Long id) {

        Long currentUserId = SecurityUtils.getCurrentUserId();

        // 检查用户是否为团队成员
        if (!teamMemberService.isTeamMember(id, currentUserId)) {
            return ApiResponse.error("您不是该团队成员");
        }

        try {
            // 获取团队所有成员
            List<TeamMember> teamMembers = teamMemberService.getTeamMembers(id);

            // 提取成员用户ID
            List<Long> memberUserIds = teamMembers.stream()
                .map(TeamMember::getUserId)
                .collect(Collectors.toList());

            // 获取成员在线状态
            Map<Long, Map<String, Object>> onlineStatusMap =
                userOnlineService.getTeamMembersOnlineStatus(memberUserIds);

            // 组装响应数据
            List<Map<String, Object>> membersWithStatus = teamMembers.stream()
                .map(member -> {
                    Map<String, Object> memberInfo = new HashMap<>();
                    memberInfo.put("userId", member.getUserId());
                    memberInfo.put("nickname", member.getNickname());
                    memberInfo.put("username", member.getUsername());
                    memberInfo.put("role", member.getRole());
                    memberInfo.put("joinTime", member.getJoinTime());

                    // 添加在线状态信息
                    Map<String, Object> onlineStatus = onlineStatusMap.get(member.getUserId());
                    if (onlineStatus != null) {
                        memberInfo.put("isOnline", onlineStatus.get("isOnline"));
                        memberInfo.put("lastActiveTime", onlineStatus.get("lastActiveTime"));
                        memberInfo.put("status", onlineStatus.get("status"));
                    } else {
                        memberInfo.put("isOnline", false);
                        memberInfo.put("status", "OFFLINE");
                    }

                    return memberInfo;
                })
                .collect(Collectors.toList());

            // 统计在线成员数量
            long onlineCount = membersWithStatus.stream()
                .mapToLong(member -> (Boolean) member.get("isOnline") ? 1 : 0)
                .sum();

            Map<String, Object> responseData = new HashMap<>();
            responseData.put("teamId", id);
            responseData.put("members", membersWithStatus);
            responseData.put("totalMembers", membersWithStatus.size());
            responseData.put("onlineMembers", onlineCount);
            responseData.put("updateTime", LocalDateTime.now());

            return ApiResponse.success("获取团队成员在线状态成功", responseData);

        } catch (Exception e) {
            logger.error("获取团队成员在线状态失败: teamId={}", id, e);
            return ApiResponse.error("获取团队成员在线状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取团队设置
     */
    @Operation(summary = "获取团队设置", description = "获取团队的高级设置信息")
    @GetMapping("/{id}/settings")
    @RequirePermission(Permission.TEAM_MANAGE)
    public ApiResponse<TeamSettingsResponse> getTeamSettings(@PathVariable Long id) {
        logger.info("获取团队设置: teamId={}", id);

        Long userId = SecurityUtils.getCurrentUserId();

        // 检查用户是否可以管理团队设置（OWNER或ADMIN）
        if (!teamMemberService.canManageTeamSettings(id, userId)) {
            return ApiResponse.error("只有团队所有者和管理员可以查看团队设置");
        }

        try {
            Team team = teamService.getTeamSettings(id);
            TeamSettingsResponse response = TeamSettingsResponse.from(team);
            return ApiResponse.success("获取团队设置成功", response);
        } catch (Exception e) {
            logger.error("获取团队设置失败: teamId={}", id, e);
            return ApiResponse.error("获取团队设置失败: " + e.getMessage());
        }
    }

    /**
     * 更新团队设置
     */
    @Operation(summary = "更新团队设置", description = "更新团队的高级设置信息")
    @PutMapping("/{id}/settings")
    @RequirePermission(Permission.TEAM_MANAGE)
    public ApiResponse<TeamSettingsResponse> updateTeamSettings(@PathVariable Long id,
                                                       @Valid @RequestBody TeamSettingsRequest request) {
        logger.info("更新团队设置: teamId={}, request={}", id, request);

        Long userId = SecurityUtils.getCurrentUserId();

        // 检查用户是否可以管理团队设置（OWNER或ADMIN）
        if (!teamMemberService.canManageTeamSettings(id, userId)) {
            return ApiResponse.error("只有团队所有者和管理员可以更新团队设置");
        }

        try {
            Team updatedTeam = teamService.updateTeamSettings(id, request);
            TeamSettingsResponse response = TeamSettingsResponse.from(updatedTeam);
            return ApiResponse.success("团队设置更新成功", response);
        } catch (Exception e) {
            logger.error("更新团队设置失败: teamId={}", id, e);
            return ApiResponse.error("更新团队设置失败: " + e.getMessage());
        }
    }

    /**
     * 检查团队对用户的可见性
     */
    @Operation(summary = "检查团队可见性", description = "检查团队对当前用户是否可见")
    @GetMapping("/{id}/visibility")
    public ApiResponse<Map<String, Object>> checkTeamVisibility(@PathVariable Long id) {
        logger.info("检查团队可见性: teamId={}", id);

        Long userId = SecurityUtils.getCurrentUserId();

        try {
            boolean isVisible = teamService.isTeamVisibleToUser(id, userId);
            boolean isMember = teamMemberService.isTeamMember(id, userId);

            Map<String, Object> result = new HashMap<>();
            result.put("teamId", id);
            result.put("isVisible", isVisible);
            result.put("isMember", isMember);
            result.put("userId", userId);

            return ApiResponse.success("检查团队可见性成功", result);
        } catch (Exception e) {
            logger.error("检查团队可见性失败: teamId={}", id, e);
            return ApiResponse.error("检查团队可见性失败: " + e.getMessage());
        }
    }


}
